package com.mibao.db;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.mibao.sketch.HideAppItem;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;

public class DBAdapter{
    private final Context Ctx;
    private DBHelper helper;
    private SQLiteDatabase db;
    
    private String table1 = "mibao_user_friend";
    private String table2 = "mibao_user_record";
    private String table3 = "mibao_user_app";
    private String table4 = "mibao_user_message";
   
    public DBAdapter(Context ctx){
    	this.Ctx = ctx;
    }
    public DBAdapter open() throws SQLException {
    	helper = new DBHelper(Ctx);
        db = helper.getWritableDatabase();
    	return this;
    }
    
    //获取拨号密码
    public String getPassword() {
        String password = "";
        String sql = "SELECT id, password FROM mibao_user_info";
        Cursor appCursor = db.rawQuery(sql, null);
        while (appCursor.moveToNext()) {
            password = appCursor.getString(1);
        }
        appCursor.close();
        return password;
    }

     //插入拨号密码
    public boolean insertPwd(String password) {
        try {
            String sql = "INSERT INTO mibao_user_info" + "(password) " + "VALUES(?)";
            SQLiteStatement stat = db.compileStatement(sql);
            db.beginTransaction();
            int count = this.getCountOfData();
            if (count > 0) {
                db.execSQL("DELETE FROM mibao_user_info");
                revertSeq();
            }
            stat.bindString(1, password);
            long result = stat.executeInsert();
            if (result < 0) {
                return false;
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (null != db) {
                    db.endTransaction();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    //查询表
    public Cursor select(int flag){
    	Cursor cursor = null;
    	switch(flag){
    	case 1:
    		cursor = db.query(table1, null, null, null, null, null, null);
    		break;
    	case 2:
    		cursor = db.query(table2, null, null, null, null, null, null);
    		break;
    	case 3:
    		cursor = db.query(table3, null, null, null, null, null, null);
    		break;
    	case 4:
    		cursor = db.query(table4, null, null, null, null, null, null);
    		break;
    	default:
    		break;
    	}
    	return cursor;
    }
    //插入联系人
    public long insertPhone(String nameTemp,String phoneTemp){
    	ContentValues cv = new ContentValues();
    	cv.put("phone", phoneTemp);
    	cv.put("name", nameTemp);
    	long row = db.insert(table1, null, cv);
    	return row;
    }
    //删除联系人
    public void deletePhone(String phone){
    	String where = "phone" + "=?";
    	String[] whereValue = {phone};
    	db.delete(table1, where, whereValue);
    }
    //编辑联系人
    public void editPhone(String nameTemp,String phoneTemp){
        String where = "name"+"=?";
        String[] whereValue = {nameTemp};
        
        ContentValues cv = new ContentValues();
        cv.put("phone", phoneTemp);
    	cv.put("name", nameTemp);
    	db.update(table1, cv, where, whereValue); 
    }
    //拦截记录数据
    
    //插入app 数据（批量添加）
    public void Sql_hideAppIcon(ArrayList<HideAppItem> hideAppItems){
    	BitmapDrawable bd = null;
    	Bitmap icon = null;
    	for(int i =0;i<hideAppItems.size();i++){
    		bd   = (BitmapDrawable)hideAppItems.get(i).icon;
    		icon = bd.getBitmap();
    		ByteArrayOutputStream os = new ByteArrayOutputStream();
    		icon.compress(Bitmap.CompressFormat.PNG, 100, os);
    		ContentValues cv = new ContentValues();
    		cv.put("appName", hideAppItems.get(i).getAppName());
    		cv.put("packageName", hideAppItems.get(i).getPkgName());
    		cv.put("appIcon", os.toByteArray());
    		db.update(table3, cv, null, null);
    	}
    }
    //删除某隐藏的app 函数重载（批量删除一些隐藏的app）
    public void Sql_CancelhideAppIcon(List<String> DisplayAppList){
    	String where = "packageName" + "=?";
    	for(int i = 0;i<DisplayAppList.size();i++){
    		String[] whereValue = {DisplayAppList.get(i)};
        	db.delete(table3, where, whereValue); 
    	}
    }
    //删除某隐藏的app 函数重载（删除一个隐藏的app）
    public void Sql_CancelhideAppIcon(String DisplayApp){
    	String where = "packageName" + "=?";
        String[] whereValue = {DisplayApp};
        db.delete(table3, where, whereValue); 
    }
    //插入短信消息记录
    public long InsertMessage(String phone,String message){
    	
    	ContentValues cv = new ContentValues();
    	cv.put("phone", phone);
    	cv.put("message", message);
    	cv.put("flag", message);
    	long row = db.insert(table4, null, cv);
    	return row;
    }
    //删除短信消息记录
    public void DeleteMessage(String phone,int id){
    	
    }
    private void revertSeq() {
        String sql = "update sqlite_sequence set seq=0 where name='mibao_user_info'";
        db.execSQL(sql);
    }

    
    //获取记录数
    public int getCountOfData() {
        String sql = "SELECT COUNT(id) FROM mibao_user_info";
        Cursor appCursor = db.rawQuery(sql, null);
        int count = 0;
        while (appCursor.moveToNext()) {
            count = appCursor.getInt(0);
        }
        return count;
    }
    
    public void close(){
    	helper.close();
    }
}
